package com.dingpeikeji.quickdeer.modules.rentproduct.web;

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.utils.MD5Utils;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.line.entity.TLine;
import com.dingpeikeji.quickdeer.core.modules.line.service.TLineService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Area;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.modules.base.web.FSysController;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotypeForsale;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeForsaleService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.google.common.collect.Lists;
import com.opensymphony.module.sitemesh.html.tokenizer.TagTokenizer;
import com.sun.mail.handlers.text_html;


/**
 * 整车预定
 *
 */
@Controller
@RequestMapping(value = { "/f/rentproduct" })
public class FRentproductController extends BaseController {

	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private TCargotypeService tCargotypeService;
	@Autowired
	private TRentgroupService tRentgroupService;
	@Autowired
	private TLineService tLineService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private OfficeService officeService;

	/**
	 * 整车预订列表页
	 */
	@RequestMapping("list")
	public String list(TRentproduct tRentproduct, HttpServletRequest request, 
			HttpServletResponse response, Model model,TCargotype tCargotype)
			throws Exception {
		//防止跨市,0.5天
		if (tRentproduct.getDaysnum()==null) {
			tRentproduct.setDaysnum(1);
		}
		if (tRentproduct.getDaysnum()==0&&"跨市".equals(tRentproduct.getTabType())) {
			tRentproduct.setDaysnum(1);
			tRentproduct.setTabType("跨市");
		}
		String viewPage = "modules/rentproduct/fRentproductFor{0}List"; // 视图
		//获取车型
		String tstyle = request.getParameter("tstyle");
		tCargotype.setTstyles(tstyle);
		tRentproduct.setCargotype(tCargotype);
		// 消息集合
		List<String> messages = Lists.newArrayList();
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model)
				// 包车天数为空，1天-10天选择，默认1天
				.handleDaysnum();
		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if (warningFor2Hours != null) {
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}
		// 根据包车天数计算租赁结束日期
		String warningFor3Month = tRentproduct.handle3MonthWarning();
		if (warningFor3Month != null) {
			messages.add(warningFor3Month);
		}
		// 当前下午2点停止卖票
		if (messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if (warningFor14Hours != null) {
				messages.add(warningFor14Hours);
			}
		}
		List<TRentproduct> rentproductList = null;
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		//查询线路包含的车型
		// 分页对象
		Page<TCargotype> page = new Page<TCargotype>(request, response);
		tCargotype.setPage(page);
		page.setPageSize(6);
		//跨市range=2,市内range=1(t_rentgroup表)
		if(tRentproduct.getTabType().equals("市内")){
			tCargotype.setRange("1");
		}else{
			tCargotype.setRange("2");
		}
		List<TCargotype> cargotypes = rentproductService.findCargotypeList(tCargotype);
		page.setList(cargotypes);
		if (messages.isEmpty()) {
			//获取车型id,查询对应的线路报价
			if (cargotypes.size()>0) {
				for (TCargotype tc : cargotypes) {
					tRentproduct.setCargotype(tc);
					// 市内日租包车
					if (TOrders.ORDER_TYPE_RENTPRODUCT_DAY.equals(tRentproduct.getRentType())
							&& tRentproduct.getTabType().equals("市内")) {
						rentproductList = rentproductService.findInCityList(tRentproduct);
					}
					// 跨城日租包车
					if (TOrders.ORDER_TYPE_RENTPRODUCT_DAY.equals(tRentproduct.getRentType())
							&& tRentproduct.getTabType().equals("跨市")) {
						rentproductList = rentproductService.findBetweenCityList(tRentproduct);
					}
					tc.setRentproductList(rentproductList);
				}
			}
		} else {
			request.getSession().setAttribute("mes", messages.get(0));
		}
		formatDate(model);
		model.addAttribute("tstyle", tstyle);
		model.addAttribute("cargotypeList", cargotypes);
		model.addAttribute("rentproductList", rentproductList);
		model.addAttribute("page", page);
		model.addAttribute("tRentproduct", tRentproduct);
		//String formatPage = MessageFormat.format(viewPage, rentproductService.getRentTypeName(tRentproduct.getRentType()));
		return "modules/base/indexDayRentResult";//modules/rentproduct/fRentproductForTravelList
	}
	/**
	 * 接送机
	 */
	@RequestMapping("airlist")
	public String airList(TRentproduct tRentproduct, HttpServletRequest request, 
			HttpServletResponse response, Model model,TCargotypeForsale cargotypeForsale)
					throws Exception {
		// 消息集合
		List<String> messages = Lists.newArrayList();
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model)
				// 包车天数为空，1天-10天选择，默认1天
				.handleDaysnum();
		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if (warningFor2Hours != null) {
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}
		// 当前下午2点停止卖票
		if (messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if (warningFor14Hours != null) {
				messages.add(warningFor14Hours);
			}
		}
		// 根据包车天数计算租赁结束日期
		String warningFor3Month = tRentproduct.handle3MonthWarning();
		if (warningFor3Month != null) {
			messages.add(warningFor3Month);
		}
		if (!messages.isEmpty()) {//发车时间
			request.getSession().setAttribute("mes", messages.get(0));
			formatDate(model);
			model.addAttribute("tRentproduct", tRentproduct);
			return "modules/base/indexPickSend";
		}
		String mes = request.getParameter("mes");
		String destSiteName = request.getParameter("destcity.sitename");
		String detailAddress = request.getParameter("aboardAddress");
		if (StringUtils.isEmpty(mes)) {//没有搜索结果返回页面
			request.getSession().setAttribute("mes", "暂无搜索结果,请尝试更换新的地址");
			formatDate(model);
			return "modules/base/indexAirRent";
		}
		tRentproduct.setRemarks(mes);
		//获取车型
		TCargotype cargotype = new TCargotype();
		String tstyle = request.getParameter("tstyle");
		cargotypeForsale.setCargotype(cargotype);
		cargotypeForsale.getCargotype().setTstyles(tstyle);
		//百度地图自动赋值城市名称,根据名称查询
		TSitedtl sitedtl = tSitedtlService.getDestCityByName(tRentproduct.getDestcity().getSitename());
		if (sitedtl!=null) {
			tRentproduct.setDestcity(sitedtl);//不匹配,重新赋值
			cargotypeForsale.setDepartcity(tRentproduct.getDepartcity());
			cargotypeForsale.setDestcity(tRentproduct.getDestcity());
		}else{
			tRentproduct.setDestcity(null);//查询不到目的地
			cargotypeForsale.setDepartcity(tRentproduct.getDepartcity());
			cargotypeForsale.setDestcity(tRentproduct.getDestcity());
		}
		//产品名称
		String productName = "";
		if (tRentproduct.getDestcity()!=null) {
			productName = tRentproduct.getDepartcity().getSitename()
					+"-"+tRentproduct.getDestcity().getSitename()+"("+tRentproduct.getTabType()+")";
		}else{
			productName = tRentproduct.getDepartcity().getSitename()
					+"-"+destSiteName+"("+tRentproduct.getTabType()+")";
		}
		tRentproduct.setProductname(productName);
		tRentproduct.setAboardAddress(detailAddress);
		String kms = tRentproduct.getMapkm();//地图测算的距离
		double distance = 0.0;
		int disLevel = 0;
		if (StringUtils.isNotEmpty(kms)) {
			if (kms.indexOf("公里")!=-1) {
				distance = Double.parseDouble(kms.substring(0, kms.indexOf("公里")));
				if (distance<=50&&distance>=0) {
					disLevel = 1;
				}else if (distance<=150&&distance>50) {
					disLevel = 2;
				}else if (distance<=275&&distance>150) {
					disLevel = 3;
				}else if (distance<=500&&distance>275) {
					disLevel = 4;
				}else {
					disLevel = 5;
				}
			}else{
				disLevel = 1;//距离太近,取不到公里数
			}
		}
		
		String maptime = tRentproduct.getMaptime();//地图测算的距离
		//根据出发地,目的地 查询所有车型
		Page<TCargotypeForsale> page = new Page<TCargotypeForsale>(request, response);
		page.setPageSize(5);
		cargotypeForsale.setPage(page);
		List<TCargotypeForsale> cargotypeList = rentproductService.findAirCargotypeList(cargotypeForsale);
		page.setList(cargotypeList);
		List<Office> officeList = null;
		//根据车型获取对应的车队
		if (cargotypeList.size()>0&&cargotypeList!=null) {
			for (TCargotypeForsale tc : cargotypeList) {
				double condition0 = ((tc.getCargotype().getNudePrice()/2.00+100)+
						(tc.getCargotype().getOilcost()+tc.getCargotype().getRoadmodules())*distance*2);
				double condition1 = (tc.getCargotype().getNudePrice()+
						(tc.getCargotype().getOilcost()+tc.getCargotype().getRoadmodules())*distance*2);
				double condition2 = (((tc.getCargotype().getNudePrice()+300)*(distance/500+1))+
						(tc.getCargotype().getOilcost()+tc.getCargotype().getRoadmodules())*distance*2);

				Set<Double> priceSet = new TreeSet<Double>();
				List<Double> priceList = new ArrayList<Double>();
				tc.setDepartcity(tRentproduct.getDepartcity());
				tc.setDestcity(tRentproduct.getDestcity());
				tc.setDisLevel(disLevel);//距离等级
				officeList = rentproductService.findAirProductByType(tc);
				if (officeList.size()>0&&officeList!=null) {
					for (Office office : officeList) {
						if (distance<=50&&distance>=0) {
							office.setAirPrice(Math.ceil(condition0*office.getFactor()));
						}else if(distance<=500&&distance>50) {
							office.setAirPrice(Math.ceil(condition1*office.getFactor()));
						}else {
							office.setAirPrice(Math.ceil(condition2*office.getFactor()));
						}
						}
				}
				tc.setOfficeList(officeList);
				//取最低价
				for (Office office : officeList) {
					priceSet.add(office.getAirPrice());
				}
				for (Double double1 : priceSet) {
					priceList.add(double1);
				}
				if (priceList.size()>0) {
					tc.setLowestAirPrice(priceList.get(0));
				}
			}
		}
		formatDate(model);
		model.addAttribute("cargotypeList", cargotypeList);
		model.addAttribute("page", page);
		model.addAttribute("mes", mes);
		model.addAttribute("kms", kms);
		model.addAttribute("maptime", maptime);
		model.addAttribute("tstyle", tstyle);
		model.addAttribute("time", tRentproduct.getTime());
		model.addAttribute("tRentproduct", tRentproduct);
		return "modules/base/indexPickSend";//modules/rentproduct/fRentproductForTravelList
	}
	
	//旅游包车预订
	@RequestMapping("travelList")
	public String travelList(TRentproduct tRentproduct,TRentgroup tRentgroup, HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {
		tRentgroup = initParam(tRentgroup, tRentproduct);//初始化周边游,目的地游
		tRentgroup.setDepartcity(tRentproduct.getDepartcity());
		String destination = request.getParameter("destination");//选择的景点
		if ("不限".equals(destination)) {
			destination = null;
		}
		tRentgroup.setDestination(destination);
		tRentgroup.setSiteid(tRentgroup.getDepartcity().getSiteid());
		tRentgroup.setSitename(tRentproduct.getDepartcity().getSitename());
		//选择的天数
		String day = request.getParameter("estday");
		if ("0".equals(day)||"不限".equals(day)||StringUtils.isEmpty(day)) {
			tRentgroup.setDaysnum(null);
		}else{
			tRentgroup.setDaysnum(Integer.parseInt(day.substring(0,1)));
		}
		// 如果发车日期为空或者小于当前日期，则设置成明天,包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		//查询天数
		List<Integer> dayList =tRentgroupService.getTravelProductDaysNum(tRentgroup);
		model.addAttribute("dayList", dayList);
		if (StringUtils.isNotEmpty(day)&&!"不限".equals(day)) {
			model.addAttribute("day", Integer.parseInt(day.substring(0,1)));
		}
		//查询包含的景点
		Set<String> allSiteList = new TreeSet<String>();
		List<String> siteList =tRentgroupService.getTravelProductSiteList(tRentgroup);
		for (String sites : siteList) {
			String[] arr = sites.split("-");
			for (int i = 0; i < arr.length; i++) {
				allSiteList.add(arr[i]);
			}
		}
		model.addAttribute("destination", destination);
		model.addAttribute("allSiteList", allSiteList);
		//分页查询
		Page<TRentgroup> page = new Page<TRentgroup>(request, response);
		tRentgroup.setPage(page);
		List<TRentgroup> rentGroupList =tRentgroupService.getTravelProducts(tRentgroup);
		page.setList(rentGroupList);
		//查询线路对应的产品
		for (TRentgroup tr : rentGroupList) {
			tRentproduct.setDepartcity(tr.getDepartcity());
			tRentproduct.setDestcity(tr.getDestcity());
			tRentproduct.setProductname(tr.getProductname());
			tRentproduct.setRentType(tr.getRenttype());
			/*double lowestPrice = rentproductService.findLowestPrice(tRentproduct);
			tr.setLowestPrice(lowestPrice);*/
		}
		model.addAttribute("page", page);
		model.addAttribute("tRentgroup", tRentgroup);
		model.addAttribute("tRentproduct", tRentproduct);
		return "modules/base/indexTravelRentResult";
	}

	private void formatDate(Model model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		model.addAttribute("today", sdf.format(calendar.getTime())); // 当天日期
		calendar.add(Calendar.DAY_OF_YEAR, +1);
		model.addAttribute("tomorrow", sdf.format(calendar.getTime()));
		calendar.add(Calendar.MONTH, +3);
		String format = sdf.format(calendar.getTime());
		String specifiedDayBefore = getSpecifiedDayBefore(format);
		model.addAttribute("maxDay", specifiedDayBefore);
		model.addAttribute("time", "06:00");
	}

	public static String getSpecifiedDayBefore(String specifiedDay) {
		Calendar c = Calendar.getInstance();
		Date date = null;
		try {
			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day - 1);
		String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
		return dayBefore;
	}

	private TRentgroup initParam(TRentgroup tRentgroup, TRentproduct tRentproduct) {
		if (tRentproduct.getTabType().contains("周边游包车")) {
			tRentproduct.setTabType("周边游包车");
			tRentproduct.setAnothertabType("目的地包车");
			tRentgroup.setTraveltype(1);
		}else if(tRentproduct.getTabType().contains("目的地包车")){
			tRentproduct.setTabType("目的地包车");
			tRentproduct.setAnothertabType("周边游包车");
			tRentgroup.setTraveltype(2);
		}else{
			tRentgroup.setTraveltype(1);
			tRentproduct.setTabType("周边游包车");
			tRentproduct.setAnothertabType("目的地包车");
		}
		return tRentgroup;
	}
	/**
	 * 整车预定详情页
	 */
	@RequestMapping("traveldetails")
	public String travelDetails(TRentproduct tRentproduct, Model model,TCargotype tCargotype,
			TRentgroup tRentgroup,TLine tLine,HttpServletRequest request,HttpServletResponse response) throws Exception {
		// 如果发车日期为空或者小于当前日期，则设置成明天,包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		//获取车型
		String tstyle = request.getParameter("tstyle");
		tCargotype.setTstyles(tstyle);
		tRentproduct.setCargotype(tCargotype);
		//获取线路描述
		String description = tRentgroupService.getDescriptionById(tLine.getLinename());
		//description = description.replaceAll("您可以参照上述行程，自由选择景点游玩时间和行程顺序", "");
		description = description.replaceAll("&nbsp;", "");
		tRentgroup.setDescription(description);
		String[] arr = description.split("第"+"\\S"+"天");
		Map<Long, String> map = new HashMap<Long, String>();
		List<Long> list = formatDesc(arr, map);
		//初始化TRentproduct
		tRentproduct.getDepartcity().setSiteid(tRentproduct.getDepartcity().getId());
		tRentproduct.getDestcity().setSiteid(tRentproduct.getDestcity().getId());
		tRentproduct.setProductname(tLine.getLinename());
		//初始化tcargotype
		tCargotype.getDepartcity().setSiteid(tRentproduct.getDepartcity().getId());
		tCargotype.getDestcity().setSiteid(tRentproduct.getDestcity().getId());
		tCargotype.setProductname(tLine.getLinename());
		// 分页对象
		Page<TCargotype> page = new Page<TCargotype>(request, response);
		page.setPageSize(5);
		tCargotype.setPage(page);
		//查询线路所拥有的车型
		List<TCargotype> cargotypeList = rentproductService.getCargotypeList(tCargotype);
		page.setList(cargotypeList);
		tRentproduct.setCargotypeList(cargotypeList);
		//获取车型id,查询对应的线路报价
		List<TRentproduct> rentproductList = null;
		if (cargotypeList.size()>0) {
			for (TCargotype tc : cargotypeList) {
				tRentproduct.setCargotype(tc);
				rentproductList = rentproductService.findTravelList(tRentproduct);
				tc.setRentproductList(rentproductList);
			}
		}
		// 整车查询列表
		//List<TRentproduct> rentproductList = rentproductService.findTravelList(tRentproduct);
		
		
		model.addAttribute("page", page);
		request.setAttribute("list", list);
		model.addAttribute("tRentgroup", tRentgroup);
		model.addAttribute("tstyle", tstyle);
		model.addAttribute("tRentproduct", tRentproduct);
		model.addAttribute("cargotypeList", cargotypeList);
		model.addAttribute("map", map);
		model.addAttribute("tLine", tLine);
		//return MessageFormat.format(viewPage, rentproductService.getRentTypeName(tRentproduct.getRentType()));
		return "modules/base/indexTravelRentDetail";
	}

	private List<Long> formatDesc(String[] arr, Map<Long, String> map) {
		//el表达式中数字1是Long类型，无法匹配后台map中的int。
		//修改 map.put(0L, value);  前台 ：${map[1]}.
		List<Long> list = new ArrayList<Long>();
		long i = 1;
		for (String s : arr) {
			if (StringUtils.isEmpty(s)||s.length()==0||"".equals(s)) {
				continue;
			}
			map.put(i, s.substring(1).replaceAll(" {2,}", ""));//X{n,} X，至少 n 次
			i++;
			list.add(i);
		}
		return list;
	}

	/**
	 * 整车预定详情页
	 */
	@RequestMapping("details")
	public String details(TRentproduct tRentproduct, Model model, HttpServletRequest request,HttpServletResponse response) throws Exception {
		User user = (User) request.getSession().getAttribute(FSysController.FRONT_USER_IN_SESSION);
		String viewPage = "modules/rentproduct/fRentproductFor{0}Details"; // 视图

		// 根据ID查询选中的整车信息
		TRentproduct rentproduct = tRentproductService.get(tRentproduct.getRentid());
		TRentgroup rentgroup = tRentgroupService.get(rentproduct.getRentgrpid());

		if (rentproduct != null) {
			// 协议价逻辑处理
			TRentproduct query = new TRentproduct();
			query.setRentid(tRentproduct.getRentid());
			if (StringUtils.isEmpty(tRentproduct.getTime())) {
				tRentproduct.setTime("06:00");//默认6点
			}
			query.setDepartdate(DateUtils.parseDate(tRentproduct.getFromdateStr() + " " + tRentproduct.getTime()));
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
			rentproduct.setSuitrtnprice(query.getSuitrtnprice());
		}

		// 数据校验

		// 消息集合
		List<String> messages = Lists.newArrayList();

		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);

		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if (warningFor2Hours != null) {
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}

		// 当前下午2点停止卖票
		if (messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if (warningFor14Hours != null) {
				messages.add(warningFor14Hours);
			}
		}

		if (!messages.isEmpty()) {
			addMessage(model, messages.toArray(new String[] {}));
		}

		model.addAttribute("tRentproduct", rentproduct);
		model.addAttribute("rentgroup", rentgroup);
		model.addAttribute("query", tRentproduct);
		model.addAttribute("user", user);
		if ("5".equals(tRentproduct.getRentType())) {//旅游包车跳转页面
			formatDate(model);
			Double suitrtnprice = rentproduct.getSuitrtnprice();
			response.getWriter().println(suitrtnprice);
			return "/modules/rentproduct/fRentproductForTravelBook";
		}
		String format = MessageFormat.format(viewPage, rentproductService.getRentTypeName(tRentproduct.getRentType()));
		return format;
	}
	/**
	 * 根据时间计算出当前的价格
	 */
	@RequestMapping("getPrice")
	public void getPrice(TRentproduct tRentproduct, Model model, HttpServletRequest request,HttpServletResponse response) throws Exception {
		// 根据ID查询选中的整车信息
		TRentproduct rentproduct = tRentproductService.get(tRentproduct.getRentid());
		
		if (rentproduct != null) {
			// 协议价逻辑处理
			TRentproduct query = new TRentproduct();
			query.setRentid(tRentproduct.getRentid());
			if (StringUtils.isEmpty(tRentproduct.getTime())) {
				tRentproduct.setTime("06:00");//默认6点
			}
			query.setDepartdate(DateUtils.parseDate(tRentproduct.getFromdateStr() + " " + tRentproduct.getTime()));
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
			rentproduct.setSuitrtnprice(query.getSuitrtnprice());
		}
			Double suitrtnprice = rentproduct.getSuitrtnprice();
			response.getWriter().println(suitrtnprice);
	}

	/**
	 * 生成订单
	 */
	@RequestMapping("booking")
	public String booking(TOrders orders, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request) throws ParseException {
		String redirctPage = "redirect:/f/rentproduct/details?repage&time={0}&daysnum={1}&rentid={2}&rentType={3}&fromdateStr={4}"; // 订单信息页
		String payWayPage = "redirect:/f/pay/payWay?orderid={0}"; // 支付方式选择页

		User user = (User) request.getSession().getAttribute(FSysController.FRONT_USER_IN_SESSION);
		orders.setOrderuserid(user.getId());

		// 校验数据

		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		if (ValidateTool.isEmptyOrNull(orders.getPurchasenum())) {
			messages.add("请填写车辆数");
		} else if (!ValidateTool.isNonnegativeDigit(orders.getPurchasenum())) {
			messages.add("车辆数量不正确");
		}
		if (ValidateTool.isEmptyOrNull(orders.getBoardaddr())) {
			messages.add("请填写上车地点");
		}
		if (ValidateTool.isEmptyOrNull(orders.getContacts())) {
			messages.add("请填写联系人姓名");
		}
		if (ValidateTool.isEmptyOrNull(orders.getOrdertype())) {
			messages.add("未知用途的订单");
		}
		if (ValidateTool.isEmptyOrNull(orders.getPayertel())) {
			messages.add("请填写联系电话");
		} else if (!ValidateTool.isMobile(orders.getPayertel())) {
			messages.add("电话号码不正确");
		}

		TRentproduct tRentproduct = new TRentproduct();
		tRentproduct.setFromdateStr(orders.getFromdateStr());
		tRentproduct.setTime(orders.getTime());
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);

		// 发车时间-2<=当前时间
		String warningFor2Hours = tRentproduct.handle2HoursWarning();
		if (warningFor2Hours != null) {
			messages.add(warningFor2Hours);
		} else {
			// 发车时间+12<=当前时间，添加警告信息
			tRentproduct.handle12HoursWarning(model);
		}

		// 当前下午2点停止卖票
		if (messages.isEmpty()) {
			String warningFor14Hours = tRentproduct.handle14HoursWarning();
			if (warningFor14Hours != null) {
				messages.add(warningFor14Hours);
			}
		}

		if (messages.isEmpty()) {
			// 协议价逻辑处理

			TRentproduct query = new TRentproduct();
			query.setRentid(Integer.parseInt(orders.getRealscheid()));
			query.setDepartdate(DateUtils.parseDate(orders.getDepartdateStr()));

			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
			orders.setDueamount("" + query.getSuitrtnprice());
			Integer purchasenum = Integer.valueOf(orders.getPurchasenum());
			if (orders.getOrdertype().equals(TOrders.ORDER_TYPE_RENTPRODUCT_DAY)) {
				orders.setDueamount("" + query.getSuitrtnprice() * orders.getBookingdays() * purchasenum);
			} else {
				orders.setDueamount("" + query.getSuitrtnprice() * purchasenum);
			}

			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					return MessageFormat.format(payWayPage, orderid.toString());
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("orders", orders);
		addMessage(redirectAttributes, messages.toArray(new String[] {}));
		return MessageFormat.format(redirctPage, orders.getTime(), orders.getBookingdays().toString(),
				orders.getRealscheid().toString(), orders.getOrdertype(), orders.getFromdateStr());
	}
	/**
	 * 生成订单
	 */
	@RequestMapping("travelbooking")
	public String travelbooking(TOrders orders, Model model,TRentgroup tRentgroup, RedirectAttributes redirectAttributes,
			HttpServletRequest request,HttpServletResponse response) throws Exception {
		User user = (User) request.getSession().getAttribute(FSysController.FRONT_USER_IN_SESSION);
		TRentproduct tRentproduct = new TRentproduct();
		tRentproduct.setFromdateStr(orders.getFromdateStr());
		tRentproduct.setTime(orders.getTime());
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		//处理时间
		orders.setDepartdateStr(orders.getFromdateStr()+ " " + orders.getTime());
		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		orders.setDueamount(request.getParameter("totalPrice"));
		orders.setDetailAddress((request.getParameter("remark")));
		orders.setOrderuserid(user.getId());
		if (messages.isEmpty()) {
			// 协议价逻辑处理
			TRentproduct query = new TRentproduct();
			query.setRentid(Integer.parseInt(orders.getRealscheid()));
			query.setDepartdate(DateUtils.parseDate(orders.getDepartdateStr()));
			orders.setDepartdate(query.getDepartdate());//Fri Aug 25 06:00:00 CST 2017
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					orders.setOrderid(orderid+"");
					model.addAttribute("orders", orders);
					// 分析锁定时间
					Date createDate = new Date();
					Long lockTime = 30*60*1000L; // 30分钟的毫秒数
					Date date = new Date(); // 当前系统时间
					Long leftTime = (createDate.getTime() + lockTime - date.getTime())/1000; // 锁定剩余时间
					if(leftTime > 0) { // 订单有效的时候才显示剩余时间
						model.addAttribute("minutes", leftTime/60);
						model.addAttribute("seconds", leftTime%60);
					}
					return "/modules/rentproduct/fRentproductForTravelMent";
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		request.getSession().setAttribute("mes", messages.get(0));
		return "/modules/rentproduct/fRentproductForTravelBook";
	}
	/**
	 * 生成订单
	 */

}